import { Input, Space, Descriptions, Pagination, message, Button } from "antd";
import React from "react";
import { routerRedux } from "dva/router";
import { connect } from "dva";
import styles from "./style.less";
import {
  SwapOutlined,
  ArrowUpOutlined,
  ArrowDownOutlined
} from "@ant-design/icons";
import icon from "../../assets/images/admob.png";
import * as requesturl from "@/services/request-url";
const { Search } = Input;

const sortList = ["发布日期", "点击量"];
const typeList = [
  {
    id: 1,
    name: "全部"
  },
  {
    id: 2,
    name: "科学院"
  },
  {
    id: 3,
    name: "研究院"
  }
];
@connect(({ global }) => ({ userId: global.userId }))
class ResourceSearch extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      typeIndex: "",
      sortIndex: -1,
      pageNum: 0,
      pageSize: 5,
      total: 0,
      catalog: "",
      scientificList: [],
      title: "",
      typeList: [],
      type: "",
      orderBy: "",
      allTypeIndex: 0,
      inputValue: "",
      titleFirst: "",
      showIcon: false,
      show: <ArrowUpOutlined />
    };
  }
  //
  componentDidMount = () => {
    this.getScientificByPage();
    this.getScientificDirs();
  };
  getScientificByPage = () => {
    let { pageSize, pageNum, title, type, orderBy } = this.state;
    this.props
      .dispatch({
        type: "global/getScientificByPage",
        payload: {
          pageSize: pageSize,
          pageNum: pageNum === 0 ? 1 : pageNum,
          title: title,
          keys: "",
          desc: "",
          type: type,
          orderBy: orderBy
        }
      })
      .then(res => {
        console.log(res);
        if (res && res.data.rows.length > 0) {
          this.setState({
            scientificList: res.data.rows,
            total: res.data.total
            // titleFirst: res.data.title.charAt(0)
          });
        } else {
          this.setState({
            scientificList: [],
            total: 0
          });
        }
      });
  };
  //分页
  pageChange = (page, pageSize) => {
    console.log(page, pageSize);
    this.setState({ pageSize: pageSize, pageNum: page }, () => {
      this.componentDidMount();
    });
  };
  pageSizeChange = (current, size) => {
    // console.log(current, size);
    this.setState({ pageSize: size, pageNum: 1 }, () => {
      this.componentDidMount();
    });
  };

  //搜索
  onSearch = (value, title) => {
    console.log(value);
    this.setState(
      {
        title: value,
        pageNum: 1
      },
      () => {
        this.getScientificByPage();
      }
    );
  };
  inputChange = e => {
    this.setState({
      inputValue: e.target.value
    });
  };
  getClear = () => {
    this.setState({
      inputValue: ""
    });
  };
  handleSortChange = e => {
    this.setState(
      {
        sortIndex: Number(e.target.getAttribute("data-index")),
        showIcon: true,
        pageNum: 1
      },
      () => {
        if (this.state.sortIndex === 1) {
          if (this.state.orderBy === "") {
            this.setState(
              {
                orderBy: "visit_num desc",
                show: <ArrowUpOutlined />
              },
              () => {
                this.getScientificByPage();
              }
            );
          } else if (this.state.orderBy === "create_time") {
            this.setState(
              {
                orderBy: "visit_num desc",
                show: <ArrowUpOutlined />
              },
              () => {
                this.getScientificByPage();
              }
            );
          } else if (this.state.orderBy === "visit_num desc") {
            this.setState(
              {
                orderBy: "visit_num",
                show: <ArrowDownOutlined />
              },
              () => {
                this.getScientificByPage();
              }
            );
          } else if (this.state.orderBy === "visit_num") {
            this.setState(
              {
                orderBy: "visit_num desc",
                show: <ArrowUpOutlined />
              },
              () => {
                this.getScientificByPage();
              }
            );
          } else if (this.state.orderBy === "create_time desc") {
            this.setState(
              {
                orderBy: "visit_num",
                show: <ArrowDownOutlined />
              },
              () => {
                this.getScientificByPage();
              }
            );
          }
        }
        if (this.state.sortIndex === 0) {
          if (this.state.orderBy === "") {
            this.setState(
              {
                orderBy: "create_time desc",
                show: <ArrowUpOutlined />
              },
              () => {
                this.getScientificByPage();
              }
            );
          } else if (this.state.orderBy === "visit_num") {
            this.setState(
              {
                orderBy: "create_time desc",
                show: <ArrowUpOutlined />
              },
              () => {
                this.getScientificByPage();
              }
            );
          } else if (this.state.orderBy === "create_time desc") {
            this.setState(
              {
                orderBy: "create_time",
                show: <ArrowDownOutlined />
              },
              () => {
                this.getScientificByPage();
              }
            );
          } else if (this.state.orderBy === "create_time") {
            this.setState(
              {
                orderBy: "create_time desc",
                show: <ArrowUpOutlined />
              },
              () => {
                this.getScientificByPage();
              }
            );
          } else if (this.state.orderBy === "visit_num desc") {
            this.setState(
              {
                orderBy: "create_time",
                show: <ArrowDownOutlined />
              },
              () => {
                this.getScientificByPage();
              }
            );
          }
        }
      }
    );
  };
  handleTypeChange = (code, e) => {
    this.setState(
      {
        typeIndex: code,
        type: code,
        allTypeIndex: 0,
        pageNum: 1
      },
      () => {
        console.log("this.state.type", this.state.type);

        this.getScientificByPage();
      }
    );
  };
  allhandleTypeChange = e => {
    if (this.state.allTypeIndex === 0) {
      this.setState(
        {
          allTypeIndex: 1,
          type: "",
          typeIndex: -1,
          pageNum: 1
        },
        () => {
          this.getScientificByPage();
        }
      );
    }
  };
  handleToDetaile = (id,keys,title,visitNum) => {
    // this.props.dispatch(
    //   routerRedux.push({
    //     // pathname: `/dataAssetsDetail/${id}`,
    //     pathname: `/resourceSearchDetail/${id}`,
    //     state: {
    //       id,keys,title,visitNum
    //     }
    //   })
    // );
    window.open( window.BASE_URL + `/resourceSearchDetail/${id}`)
  };
  //获取头部分类
  getScientificDirs = () => {
    this.props
      .dispatch({
        type: "global/getScientificDirs",
        payload: {
          type: "KNOWLEDGEDIRECTORY"
        }
      })
      .then(res => {
        console.log(res);
        if (res) {
          res.data.unshift({ code: "", name: "全部" });
          this.setState({
            typeList: res.data
          });
        }
      });
  };
  //下载
  download = (id, attachment) => {
    console.log(id, attachment);
    if (attachment !== "") {
      this.props.dispatch({
        type:"global/download",
        payload:{
          path: `${attachment}`
        }
      })
        .then(blob => {
          console.log("文件流", blob);
          let filename = attachment.split("/")[attachment.split("/").length - 1]
          // // let filename = decodeURI(headers["content-disposition"].split(";")[1].split("filename=")[1]);
          // let blob = new Blob(['\uFEFF' +data])
          // console.log("blob对象",blob);
          const link = document.createElement('a')
          link.download = filename
          link.style.display = 'none'
          link.href = URL.createObjectURL(blob)
          document.body.appendChild(link)
          link.click()
          URL.revokeObjectURL(link.href)
          document.body.removeChild(link)
        });
      this.props
        .dispatch({
          type: "global/Downloads",
          payload: {
            id: id
          }
        })
        .then(res => {
          console.log("789", res);
        });
    } else {
      message.error("下载资源不存在");
    }
  };

  render() {
    const {
      typeIndex,
      sortIndex,
      total,
      allTypeIndex,
      pageNum,
      showIcon,
      show,
      inputValue
    } = this.state;
    return (
      <div className={styles.content}>
        <div className={styles.bannerBox}>
          <div className={styles.bannerTitle}>
            <p>科研软件</p>
            <p>Scientific research data</p>
          </div>
        </div>
        <div className={styles.researchDataBody}>
          <div className={styles.researchDataSearch}>
            <Search
              placeholder="请输入关键字"
              onSearch={this.onSearch}
              onChange={e => this.inputChange(e)}
              value={this.state.inputValue}
            />
            <Button onClick={this.getClear}>清空</Button>
          </div>
          <div className={styles.typeBox}>
            <div className={styles.clearfix}>
              <div className={styles.fl}>
                <div className={styles.typeList}>
                  <Space>
                    <span className={styles.listLable}>分类：</span>
                    <span
                      className={allTypeIndex === 1 ? `${styles.active}` : ""}
                      onClick={e => this.allhandleTypeChange(e)}
                    ></span>
                    {this.state.typeList.map((item, index) => {
                      return (
                        <span
                          key={index}
                          data-index={index}
                          className={
                            typeIndex === item.code ? `${styles.active}` : ""
                          }
                          onClick={e => this.handleTypeChange(item.code, e)}
                        >
                          {item.name}
                        </span>
                      );
                    })}
                  </Space>
                </div>
              </div>
              <div className={styles.fr}>
                <p>
                  共检索到<span className={styles.num}>{this.state.total}</span>
                  个项目
                </p>
              </div>
            </div>
          </div>
          <div className={styles.sortBox}>
            <Space>
              {sortList.map((item, index) => {
                return (
                  <div
                    onClick={e => this.handleSortChange(e)}
                    key={index}
                    data-index={index}
                    className={
                      sortIndex === index
                        ? `${styles.active} ${styles.sortBtn}`
                        : `${styles.sortBtn}`
                    }
                  >
                    {item}
                    <span style={{ display: showIcon ? "block" : "none" }}>
                      <span
                        style={{
                          display: sortIndex === index ? "block" : "none",
                          paddingLeft: "73px",
                          marginTop: "-29px"
                        }}
                      >
                        {show}
                      </span>
                    </span>
                  </div>
                );
              })}
            </Space>
          </div>
          <div className={styles.listBox}>
            {this.state.scientificList.map((item, index) => {
              return (
                <div
                  key={index}
                  className={styles.descriptionsBox}
                  style={{ marginBottom: "2%" }}
                >
                  <div className={styles.descriptionsHead}>
                    <div className={styles.clearfix}>
                      <div className={styles.fl}>
                        <div className={styles.descriptionsIcon}>
                          {item.imgUrls !== "" ? (
                            <img src={item.imgUrls} alt="" />
                          ) : (
                            <div>{item.title.charAt(0)}</div>
                          )}
                        </div>
                      </div>
                      <div className={styles.fl}>
                        <div className={styles.descriptionsTitle}>
                          <p
                            onClick={() => this.handleToDetaile(item.id,item.keys,item.title,item.visitNum)}
                          >
                            {item.title}
                          </p>
                        </div>
                        <div className={styles.descriptionsNum}>
                          <Space size={40}>
                            <span>{item.subtitle}</span>

                            <span>点击量：{item.visitNum}</span>

                            <span>下载量: {item.downloadNum}</span>
                          </Space>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div className={styles.descriptionsBody}>
                    <Descriptions column={2}>
                      <Descriptions.Item label="软件类别">
                        {item.name}
                      </Descriptions.Item>
                      <Descriptions.Item label="添加时间">
                        {item.addTime}
                      </Descriptions.Item>
                      <Descriptions.Item label="开发者">
                        {item.author}
                      </Descriptions.Item>
                      <Descriptions.Item label="发布时间">
                        {item.releaseTime}
                      </Descriptions.Item>
                      <Descriptions.Item label="适用平台">
                        {item.platform}
                      </Descriptions.Item>
                      <Descriptions.Item label="软件大小">
                        {item.fileSize}
                      </Descriptions.Item>
                      <Descriptions.Item label="关键词" span={2}>
                        <Space className={styles.keyWords}>
                          {item.keys.split(/[，,]/).map((item, index) => {
                            return <span key={index}>{item}</span>;
                          })}
                        </Space>
                      </Descriptions.Item>
                      <Descriptions.Item label="资产介绍" span={2}>
                        <div>{item.desc}</div>
                      </Descriptions.Item>
                      {/* <div
                        dangerouslySetInnerHTML={{
                          _html: this.state.scientificList.content
                        }}
                      /> */}
                      <Descriptions.Item
                        label=""
                        span={2}
                        style={{ textAlign: "right" }}
                      >
                        <span
                          className={styles.descriptionsBtn}
                          onClick={() => this.handleToDetaile(item.id)}
                        >
                          进入详情
                        </span>
                        <span
                          className={styles.descriptionsBtn}
                          onClick={() =>
                            this.download(item.id, item.attachment)
                          }
                        >
                          立即下载
                        </span>
                      </Descriptions.Item>
                    </Descriptions>
                  </div>
                </div>
              );
            })}
            <div className={styles.pagination}>
              <Pagination
                total={total}
                showSizeChanger
                showQuickJumper
                current={pageNum === 0 ? 1 : pageNum}
                defaultCurrent={pageNum}
                defaultPageSize={5}
                pageSizeOptions={[5, 10, 20, 50]}
                showTotal={total => `共 ${total} 条`}
                onChange={this.pageChange}
                onShowSizeChange={this.pageSizeChange}
              />
            </div>
          </div>
        </div>
      </div>
    );
  }
}

export default ResourceSearch;
